/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.beans;

import com.entidades.Negocios;
import java.io.Serializable;  
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
  
import org.primefaces.event.map.OverlaySelectEvent;  
import org.primefaces.model.map.DefaultMapModel;  
import org.primefaces.model.map.LatLng;  
import org.primefaces.model.map.MapModel;  
import org.primefaces.model.map.Marker;  

@Named("mapBean")
public class MapBean implements Serializable {  
    private static final long serialVersionUID = -5634635874805070316L;
                                                
                                                 
    @PersistenceContext 
    private EntityManager em;
    
    private MapModel advancedModel;  
    private List<Negocios> vListaNegociosMapa;
    private Marker marker;  

    @PostConstruct
    public void init() {
        advancedModel = new DefaultMapModel();
        //controlBuscarOfertasMapa cbm = new controlBuscarOfertasMapa();
        //vListaNegociosMapa = cbm.findNegociosMapa();
        
        vListaNegociosMapa = findNegociosMapa();
        
        Integer posComa;
        String stLat;
        String stLng;
        LatLng coord1;
        for(int i=0;i<vListaNegociosMapa.size();i++){

            posComa = vListaNegociosMapa.get(i).getNegCoordenadas().indexOf(",");
            stLat = vListaNegociosMapa.get(i).getNegCoordenadas().substring(0,posComa);
            stLng = vListaNegociosMapa.get(i).getNegCoordenadas().substring(posComa+1);
            
            coord1 = new LatLng(Double.valueOf(stLat),Double.valueOf(stLng));
            advancedModel.addOverlay(new Marker(coord1, vListaNegociosMapa.get(i).getNegNombre()));
        
        }
        
    }
  
    
    public MapModel getAdvancedModel() {
        return advancedModel;  
    }  
      
    public void onMarkerSelect(OverlaySelectEvent event) {  
        marker = (Marker) event.getOverlay();  
        System.out.println("marcador no me jodas 2: " + marker.getTitle());
    }  
      
    public Marker getMarker() {  
        return marker;  
    }  

    public List<Negocios> findNegociosMapa() {
            
            String SQLstring;
            SQLstring = "select * from bdagrupados.negocios "
                       +" where (select count(*) from bdagrupados.ofertas where ofe_negocio = id_negocio) > 0";
            System.out.println("SQL ejecutada: " + SQLstring);
            Query query = em.createNativeQuery(SQLstring, Negocios.class);
            //Query query = em.createNamedQuery("Ofertas.findAll");
            return query.getResultList();
    }
    
}  
